package edu.tapestry.iddb.client.pages.message;

import iddb.AbstractResponse;
import iddb.BuddyPOJO;
import iddb.MessagePOJO;
import iddb.MessagesInfo;

import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import edu.tapestry.iddb.client.entities.Message;
import edu.tapestry.iddb.client.helpers.DataStorage;
import edu.tapestry.iddb.client.helpers.PI;
import edu.tapestry.iddb.client.webService.CommandsGenerator;
import edu.tapestry.iddb.client.webService.IDDBProxy;

public class SendMessage {

	@ApplicationState
	private IDDBProxy proxy;
	
	@ApplicationState
	private DataStorage storage;

	@Property
	@Persist
	private PI ident;

	@Property
	@Persist
	private Message messageToSend;
	
	@SuppressWarnings("unused")
	@Property
	private MessagePOJO message;
	
	@Inject
	private BeanModelSource beanModelSource;

	@Inject
	private ComponentResources resources;

	private BeanModel<BuddyPOJO> model;

	public Object initialize(PI ident, String toUsername) {

		this.ident = ident;
		this.messageToSend = new Message();
		this.messageToSend.setReciever(toUsername);

		return this;
	}

	void pageLoaded() {
		this.model = beanModelSource.create(BuddyPOJO.class, true, resources
				.getMessages());
		this.model.add("details", null);
	}

	public Object onActionFromSend() {
		AbstractResponse response = proxy.execute(CommandsGenerator
				.sendMessageCmd(this.ident.getIdent(), this.messageToSend.getReciever(), this.messageToSend
						.getText()));
		
		
		return this.initialize(this.ident, this.messageToSend.getReciever());
	}
	
	
	public List<MessagePOJO> getMessages(){
		MessagesInfo response = (MessagesInfo)proxy.execute(CommandsGenerator.getMessagesCmd(this.ident.getIdent()));
		storage.addMessages(this.ident, response.getList());

		return storage.getMessages(this.ident, this.messageToSend.getReciever());
	}

	public String getDateFormat(){
		return "YYYYdd";
	}
}
